package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"io/ioutil"

	"strings"

	"strconv"

	"bytes"

	"fmt"
)

func main() {
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	count := 0
	GetData := ""
	PostData := []gin.H{}

	router.GET("/", func(c *gin.Context) {
		ops := c.Query("clear")
		get := c.Query("get")
		if ops == "1" {
			GetData = ""
			count = 0
			PostData = []gin.H{}
		}
		if get == "1" {
			c.String(http.StatusOK, GetData)
		} else {
			c.JSON(200, PostData)
		}
	})

	router.GET("/get", func(c *gin.Context) {
		count += 1
		GetData += strconv.Itoa(count) + "<--------GET--------\n"
		GetData += "Header:\n"

		for k, v := range c.Request.Header {
			GetData += " " + k + ": " + strings.Join(v, " ") + "\n"

		}

		body, _ := ioutil.ReadAll(c.Request.Body)
		GetData += "\nBody:\n" + string(body) + "\n\n"

		c.String(http.StatusOK, "HelperApi V1")
	})

	router.POST("/post", func(c *gin.Context) {
		count += 1

		body, _ := ioutil.ReadAll(c.Request.Body)

		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		c.Next()

		json := make(map[string]interface{})

		headers := make(map[string]interface{})

		for k, v := range c.Request.Header {
			headers[k] = strings.Join(v, " ")
		}

		if err := c.ShouldBindJSON(&json); err == nil {
			PostData = append(PostData, gin.H{
				"count":  count,
				"header": headers,
				"data":   json,
				"time":   time.Now(),
			})
		} else {
			PostData = append(PostData, gin.H{
				"count":  count,
				"header": headers,
				"data":   string(body),
				"time":   time.Now(),
			})
		}

		c.String(http.StatusOK, "HelperApi V2")
	})

	router.Run(":8899")
}

func PostMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		data, err := ctx.GetRawData()
		if err != nil {
			fmt.Println(err.Error())
		}
		// fmt.Printf("data: %v\n", string(data))

		ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
		ctx.Next()
	}

}
